package day02.otherMethod;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

/**
 * @author chenshijie
 * @date 2023/12/15 14:24
 */

public class NettyServerForOption {
    public static void main(String[] args) {
        // 创建引导类ServerBootstrap，这个类将引导服务端的启动工作
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        // 创建两个NioEventLoopGroup类对象，可以看作传统IO编程模型的两大线程组
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();

        // handler用channel初始化器
        ChannelInitializer<ServerSocketChannel> channelInit = new ChannelInitializer<ServerSocketChannel>() {
            @Override
            protected void initChannel(ServerSocketChannel serverSocketChannel) throws Exception {
                String name = (String) serverSocketChannel.attr(AttributeKey.valueOf("appName")).get();
                System.out.println("应用名为：" + name + " 已启动");
            }
        };

        // childHandler用channel初始化器
        ChannelInitializer<SocketChannel> childChannelInit = new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                //
                System.out.println("服务器启动中,其serverName为：" + ch.attr(AttributeKey.valueOf("serverName")));
                ch.pipeline().addLast(new StringDecoder());
                ch.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
                        System.out.println(msg);
                    }
                });
            }
        };

        serverBootstrap
                .group(boss,worker)
                .channel(NioServerSocketChannel.class)
                .attr(AttributeKey.newInstance("appName"), "nettyApp")
                .childAttr(AttributeKey.newInstance("serverName"), "nettyServer")
                .handler(channelInit)
                .childHandler(childChannelInit)
                // 这个设置表示系统用于临时存放已完成三次握手的请求的队列的最大长度
                // 如果连接建立频繁，服务器处理创建新连接较慢，则可以适当调大这个参数。
                .option(ChannelOption.SO_BACKLOG, 1024)
                // true表示开启TCP底层心跳机制
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                // true表示开启Nagle算法
                // 如果要求高实时性，有数据发送时就马上发送，就设置为关闭
                // 如果要减少发送次数，减少网络交互，就设置为开启。
                .childOption(ChannelOption.TCP_NODELAY, true);
        bind(serverBootstrap, 8001);
    }

    private static void bind(final ServerBootstrap serverBootstrap, final int port) {
        serverBootstrap
                .bind(port)
                .addListener(new GenericFutureListener<Future<? super Void>>() {
                    @Override
                    public void operationComplete(Future<? super Void> future) throws Exception {
                        if (future.isSuccess()) {
                            System.out.println("端口 ["+port+"] 绑定成功！");
                        } else {
                            System.out.println("端口 ["+port+"] 绑定失败！");
                            bind(serverBootstrap, port + 1);
                        }
                    }
                });
    }
}
